import Vue from 'vue'
import App from './App'

//注册全局空提示组件
import emptyLayout from "@/components/emptyLayout.vue"
Vue.component("empty-layout", emptyLayout);
import avatar from "@/components/avatar.vue"
Vue.component("avatar", avatar);
import imageCommon from "@/components/imageCommon.vue"
Vue.component("imageCommon", imageCommon);
import mySlider from "@/components/mySlider.vue"
Vue.component("mySlider", mySlider);
import myRadioGroup from "@/components/myRadioGroup.vue"
Vue.component("myRadioGroup", myRadioGroup);
import titleCustom from "@/components/titleCustom.vue"
Vue.component("titleCustom", titleCustom);
import bodyCustom from "@/components/bodyCustom.vue"
Vue.component("bodyCustom", bodyCustom);

//导入外部引用js
import md5 from "@/js_sdk/js-md5/src/md5.js";
var FileUtils = require('js/FileUtils.js');
const qiniuUploader = require("js/qiniu/qiniuUploader.js");
const timeUtils = require("js/dateUtils.js");
const drawWordUtils = require("js/drawWordUtils.js");

import uView from 'uview-ui';
Vue.use(uView);

Vue.config.productionTip = false

App.mpType = 'app'

const app = new Vue({
	...App
})
app.$mount()

// Vue.prototype.baseUrl = 'http://192.168.0.2:8086/';
// Vue.prototype.baseUrl = 'http://localhost:10000/';
// Vue.prototype.baseUrl = 'http://192.168.0.58:8086/';
// Vue.prototype.baseUrl = 'http://192.168.50.67:8086/';//本地
// Vue.prototype.baseUrl = 'http://commontest.luozisong.top:2502/';
// Vue.prototype.baseUrl = 'http://192.168.1.100:20001/xiaotansheng/';
// Vue.prototype.baseUrl = 'http://localhost:20001/xiaotansheng/';
Vue.prototype.baseUrl = 'https://cdxf.5gsxt.cn/fireorderServer/';//线上
Vue.prototype.authUser = null;
Vue.prototype.token = null;
Vue.prototype.openid = null;
Vue.prototype.platform = null; //平台类型 0.其他 1.Android 2.iOS 3.h5 4.微信小程序 5.微信公众号  6.qq小程序
Vue.prototype.deviceBrand = null //设备品牌
Vue.prototype.lat = null; //最新定位的lat
Vue.prototype.lng = null; //最新定位的lng 
Vue.prototype.versionCode = 1; //自己定义的版本编号
Vue.prototype.auditStatus = 0; //默认审核状态 1.通过 0.审核中
Vue.prototype.lastAuditTime = null; //审核状态上次请求时间
Vue.prototype.lastSaveCidTime = null; //上次cid的保存时间
Vue.prototype.showLoginView = false; //是否已经展示了提示登录页面，为了不重复显示提示登录


Vue.prototype.isShowPromptNotice = function() { //是否已展示通知ip来判断
	let flag = uni.getStorageSync("isShowPromptNotice")
	return flag;
}
Vue.prototype.setShowPromptNotice = function(flag) { //是否已展示通知ip来判断
	uni.setStorageSync("isShowPromptNotice", flag)
}
Vue.prototype.isShowWaitTaskNotice = function() { //是否已展示通知ip来判断
	let flag = uni.getStorageSync("isShowWaitTaskNotice")
	return flag;
}
Vue.prototype.setShowWaitTaskNotice = function(flag) { //是否已展示通知ip来判断
	uni.setStorageSync("isShowWaitTaskNotice", flag)
}

Vue.filter("formatAfterTime", function(timestamp) { //传入时间戳
	return timeUtils.formatAfterTime(timestamp)
})
Vue.filter("formatAfterTime2", function(dateStr) { //传入时间格式 yyyy-MM-dd HH:mm:ss
	return timeUtils.formatAfterTime(timeUtils.getDateByTimestamp(dateStr))
})

Vue.filter("formatTimeYMD", function(dateStr) { //传入时间格式 yyyy-MM-dd HH:mm:ss
	return timeUtils.getYMDByTimestamp(timeUtils.getDateByTimestamp(dateStr))
})


Vue.filter("formatBeforeTime", function(timestamp) { //传入时间戳
	return timeUtils.formatBeforeTime(timestamp)
})
Vue.filter("formatBeforeTime2", function(dateStr) { //传入时间格式 yyyy-MM-dd HH:mm:ss
	return timeUtils.formatBeforeTime2(timeUtils.getDateByTimestamp(dateStr))
})

Vue.filter("formatBeforeTimeYMD", function(dateStr) { //传入时间格式 yyyy-MM-dd HH:mm:ss
	return timeUtils.getYMDByTimestamp(timeUtils.getDateByTimestamp(dateStr))
})


Vue.prototype.isRelease = function() { //是否是发布模式根据ip来判断
	var _this = this;
	if (this.baseUrl.indexOf("http://192.168") == 0) {
		return false;
	}
	if (this.baseUrl.indexOf("http://127.0.0.1") == 0) {
		return false;
	}
	return true;
}
Vue.prototype.md5Str = function(str) { //是否是发布模式根据ip来判断
	return md5(str);
}
Vue.prototype.initPlatform = function(str) { //是否是发布模式根据ip来判断

	if (uni.getSystemInfoSync().platform == 'devtools') { //开发者工具
		this.platform = 5
	}

	//判断平台
	// #ifdef H5
	this.platform = 3
	// #endif

	// #ifdef MP-WEIXIN
	this.platform = 4
	// #endif

	// #ifdef MP-QQ
	this.platform = 6
	// #endif

	// #ifdef MP-TOUTIAO
	this.platform = 7
	// #endif
	// #ifdef MP-KUAISHOU
	this.platform = 8
	// #endif

	// #ifdef MP-BAIDU
	this.platform = 9
	// #endif
	// let info2 = uni.getSystemInfoSync()
	// console.log(info2)
	// #ifdef APP-PLUS
	let info = uni.getSystemInfoSync()
	if (info.platform == 'android') { //注意在小程序中依然会显示使用的平台所以需要联合判断才行
		this.platform = 1
	} else if (info.platform == 'ios') {
		this.platform = 2
	} else { //这个是调试hbuilder或者是网页都会返回这个
		this.platform = 0
	}
	// #endif

	this.deviceBrand = uni.getStorageSync("deviceBrand")
	try {
		this.deviceBrand = this.deviceBrand.toLowerCase()
	} catch (e) {
		//TODO handle the exception
	}
	return this.platform
}

Vue.prototype.initAuthStatus = function(page) { //初始化审核状态
	var _this = this;

	let time = (new Date()).getTime();
	if (_this.lastAuditTime != null && time - _this.lastAuditTime < 5 * 60 * 1000 && _this.auditStatus ==
		1) { //已经过了的话则没5分钟请求一次，未通过状态下实时请求
		console.log("短时间内多次请求状态，跳过本次请求");
		return
	}

	this.lastAuditTime = time;
	this.sendRequest({
		url: "config/getAuditStatus",
		data: {
			code: _this.versionCode,
			platform: _this.platform
		},
		page: _this,
		hintCodeMsg: 2,
		showLoading: 2,
		success: function(res) {
			let status = res.data;
			// console.log(status + "    " + _this.auditStatus)
			if (status != _this.auditStatus) {
				setTimeout(function() {
					// console.log("刷新=================")
					try {
						page.onRefresh()
					} catch (e) {
						console.log(page)
					}

				}, 1000)
			}
			_this.auditStatus = status;
			uni.setStorageSync('auditStatus', _this.auditStatus);
		},
		fail: function(e) {}
	})
}

Vue.prototype.redirectToLastPage = function(page) { //重载到最新的浏览页面
	var _this = this;
	const url = uni.getStorageSync('lastUrl');
	const lastRoute = uni.getStorageSync('lastRoute');
	console.log("重载的地址  " + url)
	let homePage =
		"pages/tabbar/home;pages/tabbar/my"; //如果是首页的话则需要重定向到页面其他页面就重载
	if (homePage.indexOf(lastRoute) >= 0) { //关闭所有页面打开
		uni.reLaunch({
			url: url
		})
	} else { //关闭当前页面打开
		uni.redirectTo({
			url: url
		})
	}
}

Vue.prototype.initUser = function(option, _page, jump, loginType,
	refreshToken) { //optin页面的传值 初始化用户保证用户对象一定会有值 loginType 1.页面登录 2.弹窗登录
	var _this = this;

	if (option != null) {
		let inviteUserId = option.inviteUserId
		if (!this.isEmpty(inviteUserId)) {
			uni.setStorageSync("inviteUserId", inviteUserId)
		}
	}

	this.initPlatform();

	//处理页面传值并生成本页面的url
	let pages = getCurrentPages();
	// console.log(pages[pages.length - 1])
	let route = pages[pages.length - 1].route;
	// console.log(route)
	let ignorePage = "/pages/login/login;/pages/login/protocol"; //需要忽略的页面直接在分号后加页面的全路径就可以了
	if (ignorePage.indexOf(route) < 0 && option != null) { //避开忽略的页面
		let params = "?"; //页面携带的参数
		// console.log(option)
		if (option != null) {
			for (let pro in option) {
				if (this.isEmpty(pro))
					continue
				params = params + pro + "=" + option[pro] + "&"
			}
		}
		// #ifndef MP-KUAISHOU
		let url = "/" + route + params
		// #endif
		// #ifdef MP-KUAISHOU
		let url = route + params
		// #endif

		// console.log("当前使用的url   " + url)
		uni.setStorageSync('lastUrl', url); //当前最新的url
		uni.setStorageSync('lastRoute', route); //当前最新的url
		//延迟刷新页面测试代码
		// setTimeout(function() {
		// uni.redirectTo({
		// 	url: url
		// })
		// }, 2000)
	}

	const v = uni.getStorageSync('auditStatus');
	if (!this.isEmpty(v)) {
		this.auditStatus = v
	}

	if (this.isEmpty(loginType)) {
		loginType = 1
	}
	if (_this.authUser == null) { //当用户为空的时候去存储里面查询一下该用户是否已经存储过，是的话就取出来全局赋值
		try {
			const value = uni.getStorageSync('authUser');
			console.log(value)
			if (value != null) {
				_this.authUser = JSON.parse(value)
			}
		} catch (e) {
			// error
		}
	}

	this.token = uni.getStorageSync('token');
	// console.log("存储的token=   " + this.token)
	//如果用户还是为空的话就提示登录
	// console.log(JSON.stringify(this.authUser) + "  " + jump)
	// console.log(this.authUser == null && jump)
	if ((this.authUser == null || this.authUser.customerId == null) && jump) {
		if (_this.showLoginView) {
			return true
		}

		this.showLoginView = true;
		console.log(loginType)
		if (loginType == 1) {
			uni.redirectTo({
				url: "/pages/login/login",
				complete: function() {
					_this.showLoginView = false
				}
			})
		} else if (loginType == 2) {
			uni.showModal({
				title: '提示',
				content: "请先登录",
				confirmText: "去登录",
				showCancel: true,
				success: function(res) {

					if (res.confirm) {
						// // console.log('用户点击确定');
						// // #ifdef  H5
						_this.login(_page); //h5里登录内置的账号便于调试
						// // #endif

						// // #ifndef H5
						// _this.loginWX(_page); //小程序中登录微信	
						// // #endif
						uni.redirectTo({
							url: "/pages/login/login"
						})
						_this.showLoginView = false;
					} else if (res.cancel) {
						// console.log('用户点击取消');
						_this.showLoginView = false;
					}
				}
			});
		}

	}
	if (this.authUser == null) {
		return false
	}

	console.log(this.authUser)
	if (this.authUser != null && refreshToken) {
		// this.refreshUserToken(this.token)
	}

	uni.setStorageSync("userId", _this.authUser.id)

	return true
}
Vue.prototype.sendRequest = function(param) {
	var _this = this,
		url = param.url,
		data = param.data || {},
		header = param.header || {},
		_page = param.page,
		hintCodeMsg = param.hintCodeMsg || 1, //1.提示 2.不提示
		showLoading = param.showLoading || 1, //1.提示 2.不提示
		showLogin = param.showLogin //1提示过期登录 2.不提示 
	;
	if (this.isEmpty(showLogin)) {
		showLogin = 1;
	}
	//拼接完整请求地址
	var requestUrl = this.baseUrl + url;
	// var timestamp = Date.parse(new Date()); //时间戳

	//GET或POST
	if (param.method) {
		param.method = param.method.toUpperCase(); //小写改为大写
	}
	if (header['content-type'] == null || header['content-type'] == '') {
		header['content-type'] = "application/json;charset=utf-8";
	}

	// header['Platform'] = this.platform
	// header['Version'] = this.versionCode

	// let deviceBrand = uni.getStorageSync("deviceBrand")
	// if (!_this.isEmpty(deviceBrand)) {
	// 	header['deviceBrand'] = deviceBrand
	// }

	// header['deviceBrand'] = "huawei"

	if (this.isEmpty(this.token)) {
		this.token = uni.getStorageSync('token');
	}
	if (!_this.isEmpty(_this.token)) {
		header['token'] = '' + _this.token;
	}

	if (this.isEmpty(this.openid)) {
		this.openid = uni.getStorageSync('openid');
	}
	if (!_this.isEmpty(_this.openid)) {
		header['openid'] = '' + _this.openid;
	}
	// console.log(header)


	// console.log("header  " + JSON.stringify(_this.authUser))
	// console.log("接口使用的token  " + _this.token)

	if (showLoading == 1) {
		uni.showLoading({
			mask: true,
			title: "请求中"
		});
	}
	// console.log("请求地址  "+requestUrl)

	if (param.method == "DELETE") {
		for (let d in data) {
			if (this.isEmpty(d))
				continue
			requestUrl += "/" + data[d]
		}
	}
	// console.log(data)
	// if (data["warningRequest"] == null || data["warningRequest"] == undefined || data["warningRequest"] == '') {
	// console.log("默认请求为显示警告")
	//默认开启警告请求
	// data["warningRequest"] = "1"
	// }
	// console.log(requestUrl)
	//网络请求
	uni.request({
		url: requestUrl,
		method: param.method || "POST",
		header: header,
		data: data,
		timeout: 20000,
		xhrFields: {
			withCredentials: true
		},
		crossDomain: true,
		success: res => {
			if (showLoading == 1)
				uni.hideLoading();
			if (res.data.code == 200) { //返回结果码code判断:200成功
				typeof param.success == "function" && param.success(res.data);
			} else if (res.data.code == 505 && showLogin != 2) { //登录失效
				if (_this.showLoginView) {
					return
				}
				_this.showLoginView = true;
				let msg = res.data.msg;

				// //清除本地存储的登录数据
				// uni.setStorageSync('authUser', "");
				// uni.setStorageSync('token', "");

				// if (_this.isEmpty(_this.token)) {
				// let pages = getCurrentPages();
				// let route = pages[pages.length - 1].route;
				// // console.log(route)
				// if (route.indexOf("pages/tabbar") >= 0) {
				// 	uni.navigateTo({
				// 		url: '/pages/login/login'
				// 	});
				// } else {
				// 	uni.redirectTo({
				// 		url: '/pages/login/login'
				// 	});
				// }


				// } else {


				//展示过期登录框
				uni.showModal({
					title: '提示',
					content: "您的登录已过期请重新登录",
					confirmText: "重新登录",
					showCancel: true,
					success: function(res) {

						if (res.confirm) {
							// // console.log('用户点击确定');
							// // #ifdef  H5
							// _this.login(_page); //h5里登录内置的账号便于调试
							// // #endif

							// // #ifndef H5
							// _this.loginWX(_page); //小程序中登录微信	
							// // #endif


							uni.redirectTo({
								url: '/pages/login/login'
							});


							_this.showLoginView = false;
						} else if (res.cancel) {
							console.log('用户点击取消');
							_this.showLoginView = false;
						}
					}
				});
				// }

				if (hintCodeMsg == 1 && showLogin == 1) { //开启了提示才提示
					uni.showToast({
						title: msg,
						icon: "none",
						duration: 2000
					});
				}
			} else if (res.data.code == 1202) { //警告请求的回执
				_this.showModal({
					content: res.data.msg,
					confirmText: "继续",
					confirm: function() {
						//请求改为忽略警告，然后重新请求
						param.data.warningRequest = "0"
						// param.data = JSON.parse(JSON.stringify(data))
						console.log(param.data)
						_this.sendRequest(param)
					}
				})
				return
			} else {
				let msg = res.data.msg;
				if (hintCodeMsg == 1 && showLogin == 1 && param.codeFail ==
					null) { //开启了提示才提示
					uni.showToast({
						title: msg,
						icon: "none",
						duration: 2000
					});
				}
				typeof param.codeFail == "function" && param.codeFail(res.data);
				return;
			}

		},
		fail: (e) => {
			// let msg = e.errMsg;
			let msg = "网络超时";
			typeof param.fail == "function" && param.fail(msg);
			if (showLoading == 1)
				uni.hideLoading();
			uni.showToast({
				title: msg,
				icon: "none",
				duration: 2000
			});
		},
		complete: () => {
			let msg = "请求完成";
			typeof param.complete == "function" && param.complete(msg);
			return;
		}
	});
}

Vue.prototype.login = function(page) {
	let _this = this;
	this.sendRequest({
		url: "login/login",
		data: {
			account: "admin",
			password: "345678",
			verifyCode: "1122",
			inviteUserId: uni.getStorageSync("inviteUserId") || ""
		},
		method: "POST",
		success: function(res) {
			_this.authUser = res.data;
			_this.showLoginView = false;
			try { //同步存储用户信息
				uni.setStorageSync('authUser', JSON.stringify(_this.authUser));
				uni.setStorageSync('token', _this.authUser.token);
				_this.token = _this.authUser.token;
			} catch (e) {
				console.log('存储用户对象错误');
			}
			if (page != null)
				page.onRefresh() //调用页面自定义的刷新页面的接口
			console.log("getMachineNum success:" + JSON.stringify(res));
		},
		codeFail: function(res) {
			_this.showLoginView = false;
			uni.showModal({
				content: res.message,
				showCancel: false,
				confirmText: "确定"
			})
		},
		fail: function(e) {
			_this.showLoginView = false;
			console.log("getMachineNum  fail:" + JSON.stringify(e));
		}
	})
}

Vue.prototype.loginByVerifyCode = function(phone, verifyCode, page) {
	let _this = this;
	this.sendRequest({
		url: "api/auth/user/loginByVerifyCode",
		data: {
			phone: phone,
			verifyCode: verifyCode
		},
		success: function(res) {
			_this.authUser = res.data;
			uni.setStorageSync('showLoginView', false);
			try { //同步存储用户信息
				uni.setStorageSync('authUser', JSON.stringify(_this.authUser));
				uni.setStorageSync('token', _this.authUser.token);
				_this.token = _this.authUser.token;
			} catch (e) {
				console.log('存储用户对象错误');
			}
			if (page != null)
				page.onRefresh() //调用页面自定义的刷新页面的接口
			console.log("getMachineNum success:" + JSON.stringify(res));
		},
		codeFail: function(res) {
			uni.setStorageSync('showLoginView', false);
			uni.showToast({
				title: res.msg,
				icon: "none",
				duration: 2000
			});
			console.log("getMachineNum  fail:" + JSON.stringify(res));
		},
		fail: function(e) {
			uni.setStorageSync('showLoginView', false);
			uni.showToast({
				title: res.msg,
				icon: "none",
				duration: 2000
			});
			console.log("getMachineNum  fail:" + JSON.stringify(e));
		}
	})
}

/**动态调用每隔一天就刷新一次用户的token*/
Vue.prototype.refreshUserToken = function(lastToken) {
	let _this = this;

	// let lastTokenTime = uni.getStorageSync('lastTokenTime')
	// let currentTime = Date.parse(new Date()) / 1000
	// if (!this.isEmpty(lastTokenTime) && currentTime - lastTokenTime < (24 * 60 * 60)) { //未超过1天不刷新
	// 	return
	// }
	this.sendRequest({
		url: "api/auth/user/refreshUserToken",
		data: {
			lastToken: lastToken,
		},
		hintCodeMsg: 2,
		showLoading: 2,
		success: function(res) {
			_this.authUser = res.data;
			_this.token = _this.authUser.token
			try { //同步存储用户信息
				uni.setStorageSync('lastTokenTime', currentTime);
				uni.setStorageSync('authUser', JSON.stringify(_this.authUser));
				uni.setStorageSync('token', _this.authUser.token);
				_this.token = _this.authUser.token;
			} catch (e) {
				console.log('存储用户对象错误');
			}
		},
		codeFail: function(res) {},
		fail: function(e) {}
	})
}
// 登陆中的标记
Vue.prototype.isLogining = false;
Vue.prototype.isLoginApp = 0; //不能重复发起app登录的接口

/**小程序中登录*/
Vue.prototype.loginInWxMP = function(wxCode, infoRes, success, fail) {

	console.log(this.isLogining)
	let _this = this;
	if (this.isLogining == true) {
		return
	}
	setTimeout(function() { //5秒内不允许重复登录
		_this.isLogining = false
		_this.isLoginApp = false
	}, 2000)
	this.isLogining = true
	console.log("开始登陆进程")

	_this.sendRequest({
		url: "login/loginByWxCodePhone",
		data: {
			code: wxCode,
			codeLogin: infoRes == null ? "" : infoRes.code,
			inviteUserId: uni.getStorageSync("inviteUserId") || ""
		},
		method: "POST",
		success: function(res) {
			console.log("登录适配器")
			let data = res.data;

			_this.showLoginView = false;
			_this.isLogining = false
			try { //同步存储用户信息
				_this.loginSuccess(data, infoRes, success, fail)
			} catch (e) {
				console.log('存储用户对象错误');
				fail();
			}

		},
		codeFail: function(res) {
			_this.showLoginView = false;
			uni.showModal({
				content: res.msg,
				showCancel: false,
				confirmText: "确定"
			})
		},
		fail: function(e) {
			_this.isLogining = false
			uni.hideLoading()
			uni.showToast({
				title: "登录网络超时",
				icon: "none",
				duration: 2000
			});
			fail("登录网络超时");
		}
	})

}

/**QQ小程序中登录*/
Vue.prototype.loginInQQMP = function(infoRes, success, fail) {
	let _this = this;
	uni.showLoading({
		title: "信息处理中",
		mask: true
	})

	uni.getProvider({
		service: 'oauth',
		success: function(res) {
			console.log(JSON.stringify(res.provider))
			console.log("登录适配器")
			if (~res.provider.indexOf('qq')) {
				uni.login({
					provider: 'qq',
					success: function(loginRes) { //得到微信的code码
						_this.loginRes = loginRes;
						// console.log(_this.loginRes)
						// 获取用户信息
						// uni.getUserInfo({
						// 	provider: 'qq',
						// 	success: function(infoRes) {
						// 		// console.log('用户为：' + JSON.stringify(infoRes));

						// 	}
						// });

						_this.sendRequest({
							url: "api/auth/user/loginByQQCode",
							data: {
								code: _this.loginRes.code,
								inviteUserId: uni
									.getStorageSync(
										"inviteUserId") || ""
							},
							method: "POST",
							success: function(res) {
								uni.hideLoading();
								console.log("登录适配器")
								_this.authUser = res.data;
								//先保存token
								uni.setStorageSync('token',
									_this.authUser.token
								);
								_this.token = _this.authUser
									.token;
								_this.showLoginView = false;
								_this.isLogining = false
								// console.log(_this.authUser);
								try { //同步存储用户信息
									_this.loginSuccess(_this
										.authUser, infoRes,
										success, fail)
								} catch (e) {
									console.log('存储用户对象错误');
									fail();
								}

							},
							codeFail: function(res) {
								_this.showLoginView = false;
								uni.showModal({
									content: res.msg,
									showCancel: false,
									confirmText: "确定"
								})
							},
							fail: function(e) {
								_this.isLogining = false
								uni.hideLoading()
								uni.showToast({
									title: "登录网络超时",
									icon: "none",
									duration: 2000
								});
								fail("登录网络超时");

							}
						})
						// console.log("登录结果：" + JSON.stringify(loginRes));

					},
					fail: function(val) {
						uni.hideLoading();
						console.log(JSON.stringify(val))
						uni.showToast({
							title: "登录失败" + val.errMsg,
							icon: "none",
							duration: 2000
						});

					}
				});
			} else {
				uni.hideLoading()
			}
		},
		fail: function(val) {
			console.log(JSON.stringify(val))
			uni.showToast({
				title: "适配器获取失败" + JSON.stringify(val),
				icon: "none",
				duration: 2000
			});
		}
	});


}

/**抖音小程序中登录*/
Vue.prototype.loginInDYMP = function(success, fail) {
	let _this = this;
	uni.showLoading({
		title: "信息处理中",
		mask: true
	})

	uni.getProvider({
		service: 'oauth',
		success: function(res) {
			console.log(JSON.stringify(res.provider))
			console.log("登录适配器")
			if (~res.provider.indexOf('toutiao')) {
				uni.login({
					provider: 'toutiao',
					success: function(loginRes) { //得到微信的code码
						_this.loginRes = loginRes;
						console.log(_this.loginRes)
						// 获取用户信息
						uni.getUserInfo({
							provider: 'toutiao',
							success: function(infoRes) {
								console.log('用户为：' + JSON
									.stringify(infoRes));
								_this.sendRequest({
									url: "api/auth/user/loginByDYCode",
									data: {
										code: _this
											.loginRes
											.code,
										anonymousCode: _this
											.loginRes
											.anonymousCode,
										inviteUserId: uni
											.getStorageSync(
												"inviteUserId"
											) || ""
									},
									method: "POST",
									success: function(
										res) {
										uni
											.hideLoading();
										console.log(
											"登录适配器"
										)
										_this
											.authUser =
											res
											.data;
										//先保存token
										uni.setStorageSync(
											'token',
											_this
											.authUser
											.token
										);
										_this
											.token =
											_this
											.authUser
											.token;
										_this
											.showLoginView =
											false;
										_this
											.isLogining =
											false
										// console.log(_this.authUser);
										try { //同步存储用户信息
											_this
												.loginSuccess(
													_this
													.authUser,
													infoRes,
													success,
													fail
												)
										} catch (
											e) {
											console
												.log(
													'存储用户对象错误'
												);
											fail();
										}

									},
									codeFail: function(res) {
										_this.showLoginView = false;
										uni.showModal({
											content: res
												.msg,
											showCancel: false,
											confirmText: "确定"
										})
									},
									fail: function(e) {
										_this
											.isLogining =
											false
										uni.hideLoading()
										uni.showToast({
											title: "登录网络超时",
											icon: "none",
											duration: 2000
										});
										fail(
											"登录网络超时"
										);
									}
								})
							}
						});
						// console.log("登录结果：" + JSON.stringify(loginRes));

					},
					fail: function(val) {
						uni.hideLoading();
						console.log(JSON.stringify(val))
						uni.showToast({
							title: "登录失败" + val.errMsg,
							icon: "none",
							duration: 2000
						});

					}
				});
			} else {
				uni.hideLoading()
			}
		},
		fail: function(val) {
			console.log(JSON.stringify(val))
			uni.showToast({
				title: "适配器获取失败" + JSON.stringify(val),
				icon: "none",
				duration: 2000
			});
		}
	});
}

/**快手小程序中登录*/
Vue.prototype.loginInKSMP = function(success, fail) {
	let _this = this;
	uni.showLoading({
		title: "信息处理中",
		mask: true
	})

	uni.getProvider({
		service: 'oauth',
		success: function(res) {
			console.log(JSON.stringify(res.provider))
			console.log("登录适配器")
			if (~res.provider.indexOf('kuaishou')) {
				uni.login({
					provider: 'kuaishou',
					success: function(loginRes) { //得到微信的code码
						_this.loginRes = loginRes;
						console.log(_this.loginRes)
						// 获取用户信息
						uni.getUserInfo({
							provider: 'kuaishou',
							success: function(infoRes) {
								console.log('用户为：' + JSON
									.stringify(infoRes));
								_this.sendRequest({
									url: "api/auth/user/loginByKSCode",
									data: {
										code: _this
											.loginRes
											.code,
										inviteUserId: uni
											.getStorageSync(
												"inviteUserId"
											) || ""
									},
									method: "POST",
									success: function(
										res) {
										uni
											.hideLoading();
										console.log(
											"登录适配器"
										)
										_this
											.authUser =
											res
											.data;
										//先保存token
										uni.setStorageSync(
											'token',
											_this
											.authUser
											.token
										);
										_this
											.token =
											_this
											.authUser
											.token;
										_this
											.showLoginView =
											false;
										_this
											.isLogining =
											false
										// console.log(_this.authUser);
										try { //同步存储用户信息
											_this
												.loginSuccess(
													_this
													.authUser,
													infoRes,
													success,
													fail
												)
										} catch (
											e) {
											console
												.log(
													'存储用户对象错误'
												);
											fail();
										}

									},
									codeFail: function(res) {
										_this.showLoginView = false;
										uni.showModal({
											content: res
												.msg,
											showCancel: false,
											confirmText: "确定"
										})
									},
									fail: function(e) {
										_this
											.isLogining =
											false
										uni.hideLoading()
										uni.showToast({
											title: "登录网络超时",
											icon: "none",
											duration: 2000
										});
										fail(
											"登录网络超时"
										);
									}
								})
							}
						});
						// console.log("登录结果：" + JSON.stringify(loginRes));

					},
					fail: function(val) {
						uni.hideLoading();
						console.log(JSON.stringify(val))
						uni.showToast({
							title: "登录失败" + val.errMsg,
							icon: "none",
							duration: 2000
						});


					}
				});
			} else {
				uni.hideLoading()
			}
		},
		fail: function(val) {
			console.log(JSON.stringify(val))
			uni.showToast({
				title: "适配器获取失败" + JSON.stringify(val),
				icon: "none",
				duration: 2000
			});
		}
	});


}

/**百度小程序中登录*/
Vue.prototype.loginInBDMP = function(success, fail) {
	let _this = this;
	uni.showLoading({
		title: "信息处理中",
		mask: true
	})

	uni.getProvider({
		service: 'oauth',
		success: function(res) {
			console.log(JSON.stringify(res.provider))
			console.log("登录适配器")
			uni.getLoginCode({
				timeout: 5000,
				success: function(loginRes) { //得到微信的code码
					_this.loginRes = loginRes;
					console.log(_this.loginRes)
					_this.sendRequest({
						url: "api/auth/user/loginByBDcode",
						data: {
							code: _this
								.loginRes
								.code,
							inviteUserId: uni
								.getStorageSync(
									"inviteUserId"
								) || ""
						},
						method: "POST",
						success: function(res) {
							uni.hideLoading();
							_this.authUser = res.data;


							_this.showLoginView = false;
							_this.isLogining = false

							uni.setStorageSync('updateUserInfo', true);
							uni.hideLoading()
							try { //同步存储用户信息
								uni.setStorageSync('authUser', JSON
									.stringify(_this.authUser));
								uni.setStorageSync('token', _this
									.authUser
									.token);
								_this.token = _this.authUser.token;
								console.log(JSON
									.stringify(_this.authUser))
							} catch (e) {
								console.log('存储用户对象错误');
							}
							success()

						},
						codeFail: function(res) {
							_this.showLoginView = false;
							uni.showModal({
								content: res
									.msg,
								showCancel: false,
								confirmText: "确定"
							})
						},
						fail: function(e) {
							_this.isLogining = false
							uni.hideLoading()
							uni.showToast({
								title: "登录网络超时",
								icon: "none",
								duration: 2000
							});
							fail("登录网络超时");
						}
					})

				},
				fail: function(val) {
					uni.hideLoading();
					console.log(JSON.stringify(val))
					uni.showToast({
						title: "登录失败" + val.errMsg,
						icon: "none",
						duration: 2000
					});

				}
			});
		},
		fail: function(val) {
			console.log(JSON.stringify(val))
			uni.showToast({
				title: "适配器获取失败" + JSON.stringify(val),
				icon: "none",
				duration: 2000
			});
		}
	});
}

Vue.prototype.loginWXInApp = function(success, fail) {

	let _this = this;
	if (this.isLogining == true) {
		return
	}
	this.isLogining = true
	setTimeout(function() { //5秒内不允许重复登录
		_this.isLogining = false
		_this.isLoginApp = false
		uni.hideLoading()
	}, 5000)
	uni.showLoading({
		title: "正在登录微信",
		mask: true
	})
	uni.getProvider({
		service: 'oauth',
		success: function(res) {
			console.log(JSON.stringify(res.provider))
			console.log("登录适配器")
			if (~res.provider.indexOf('weixin')) {

				let onlyAuthorize = true
				if (_this.platform == 1) {
					onlyAuthorize = true
				} else {
					onlyAuthorize = false
				}
				uni.login({
					provider: 'weixin',
					onlyAuthorize: onlyAuthorize, // 微信登录仅请求授权认证
					success: function(loginRes) { //得到微信的code码
						console.log("登录结果：" + JSON.stringify(loginRes));
						uni.hideLoading()
						uni.showLoading({
							title: "登陆中",
							mask: true
						})
						if (_this.platform == 1) { //Android
							if (loginRes.code == null) {
								uni.showModal({
									title: "登录失败，微信登录解析失败，请重试",
									showCancel: false,
									success: function(res) {
										if (res.confirm) {
											uni.navigateBack({

											})
										}
									}
								})
								return
							}

							console.log(loginRes.code)
							_this.sendRequest({
								url: "api/auth/user/loginByWxApp",
								data: {
									code: loginRes.code,
									inviteUserId: uni.getStorageSync(
											"inviteUserId") ||
										""
								},
								method: "POST",
								success: function(res) {
									uni.hideLoading();
									console.log("登录适配器")
									_this.authUser = res.data;


									_this.showLoginView = false;
									_this.isLogining = false

									uni.setStorageSync('updateUserInfo', true);
									uni.hideLoading()
									try { //同步存储用户信息
										uni.setStorageSync('authUser', JSON
											.stringify(_this.authUser));
										uni.setStorageSync('token', _this
											.authUser
											.token);
										_this.token = _this.authUser.token;
										console.log(JSON
											.stringify(_this.authUser))
									} catch (e) {
										console.log('存储用户对象错误');
									}
									success()
								},
								codeFail: function(res) {
									_this.showLoginView = false;
									uni.showModal({
										content: res.msg,
										showCancel: false,
										confirmText: "确定"
									})
								},
								fail: function(e) {
									_this.isLogining = false
									uni.hideLoading()
									uni.showToast({
										title: "登录网络超时",
										icon: "none",
										duration: 2000
									});
									fail("登录网络超时");

								}
							})
						} else { //ios
							_this.sendRequest({
								url: "api/auth/user/loginByIOSApp",
								data: {
									openid: loginRes.authResult.openid,
									unionid: loginRes.authResult.unionid,
									type: 1
								},
								success: function(res) {
									console.log("3333333333")
									_this.authUser = res.data;
									uni.setStorageSync('showLoginView', false);
									// console.log(_this.authUser);
									try { //同步存储用户信息
										uni.setStorageSync('authUser', JSON
											.stringify(_this.authUser));
										console.log("444444")
										uni.setStorageSync('token', _this
											.authUser
											.token);
										console.log("555555555")
										_this.token = _this.authUser.token;
										// console.log(_this.authUser.token)
									} catch (e) {
										console.log('存储用户对象错误');
									}
									console.log("666666")
									if (_this.authUser
										.updateUserInfo) { //需要更新用户信息则获取一次用户信息
										// 获取用户信息
										uni.getUserInfo({
											provider: 'weixin',
											success: function(
												infoRes) {
												console.log(
													"7777777777777777"
												)
												console.log(
													'获取用户信息：' +
													JSON
													.stringify(
														infoRes
													)
												);
												_this.sendRequest({
													url: "api/auth/user/updateByUserId",
													data: {
														userId: _this
															.authUser
															.id,
														nickName: infoRes
															.userInfo
															.nickName,
														gender: infoRes
															.userInfo
															.gender,
														avatarUrl: infoRes
															.userInfo
															.avatarUrl,
													},
													success: function(
														res
													) {
														console
															.log(
																"8888888888888"
															)
														_this
															.loginSuccess(
																_this
																.authUser,
																infoRes,
																function() {
																	uni.showToast({
																		title: "登录成功",
																		icon: "none",
																		duration: 2000
																	});
																	success
																		()
																},
																function() {
																	console
																		.log(
																			"登录失败"
																		)
																	uni.showToast({
																		title: "登录网络超时",
																		icon: "none",
																		duration: 2000
																	});
																}
															)
													},
													fail: function(
														e
													) {
														uni.showToast({
															title: "登录网络超时",
															icon: "none",
															duration: 2000
														});
													}
												})

											},
											fail: function() {
												// uni.showToast({
												// 	title: "登录网络超时",
												// 	icon: "none",
												// 	duration: 2000
												// });
												uni.showToast({
													title: "登录网络超时",
													icon: "none",
													duration: 2000
												});
												console.log(
													"aaaaaaaaa"
												)
												//获取用户信息失败的话也认为登录成功，只是未更新用户信息而已
												uni.showToast({
													title: "登录成功",
													icon: "none",
													duration: 2000
												});
												try { //同步存储用户信息
													uni.setStorageSync(
														'authUser',
														JSON
														.stringify(
															_this
															.authUser
														));
													uni.setStorageSync(
														'token',
														_this
														.authUser
														.token
													);
													console.log(
														"bbbbbbbbbbbb"
													)
													_this
														.token =
														_this
														.authUser
														.token;
												} catch (e) {
													console.log(
														'存储用户对象错误'
													);
												}
												success()
											}
										});
									} else { //无需更新用户信息直接成功
										console.log("cccccccccccc")
										uni.showToast({
											title: "登录成功",
											icon: "none",
											duration: 2000
										});
										try { //同步存储用户信息
											uni.setStorageSync('authUser',
												JSON
												.stringify(_this
													.authUser));
											console.log("dddddddddddddd")
											uni.setStorageSync('token',
												_this
												.authUser.token);
											console.log("eeeeeeeeee")
											_this.token = _this.authUser
												.token;
										} catch (e) {
											console.log("ffffffff")
											console.log('存储用户对象错误');
										}
										console.log("ggggggggggggg")
										success()
									}

								},
								fail: function(e) {
									uni.showToast({
										title: "登录网络超时",
										icon: "none",
										duration: 2000
									});
								}
							})
						}


					},
					fail: function(val) {
						console.log(JSON.stringify(val))
						uni.showToast({
							title: "登录失败" + val.errMsg,
							icon: "none",
							duration: 2000
						});

					}
				});
			} else {
				uni.hideLoading()
			}
		},
		fail: function(val) {
			console.log(JSON.stringify(val))
			uni.showToast({
				title: "适配器获取失败" + JSON.stringify(val),
				icon: "none",
				duration: 2000
			});
		}
	});


}

Vue.prototype.loginApple = function(success) {

	let _this = this;
	if (this.isLogining == true) {
		return
	}
	this.isLogining = true
	setTimeout(function() { //5秒内不允许重复登录
		_this.isLogining = false
		_this.isLoginApp = false

	}, 5000)
	uni.showLoading({
		title: "正在登录苹果",
		mask: true
	})
	uni.getProvider({
		service: 'oauth',
		success: function(res) {
			console.log(res.provider)

		}
	});

	uni.login({
		provider: 'apple',
		success: function(loginRes) {
			console.log("登录成功")
			uni.hideLoading()
			// 登录成功  
			uni.getUserInfo({
				provider: 'apple',
				success(res) {
					uni.hideLoading()
					// 获取用户信息成功  
					console.log("获取信息成功  " + JSON.stringify(res))
					if (res.userInfo == null) {
						uni.showToast({
							title: "获取用户信息异常",
							icon: "none",
							duration: 2000
						});
						return
					}
					_this.sendRequest({
						url: "api/auth/user/loginByIOSApp",
						data: {
							openid: res.userInfo.openId,
							nickName: res.userInfo.fullName.familyName + res.userInfo
								.fullName.giveName,
							type: 2
						},
						success: function(res) {
							_this.authUser = res.data;
							try { //同步存储用户信息
								uni.setStorageSync(
									'authUser', JSON.stringify(_this.authUser)
								);
								uni.setStorageSync(
									'token',
									_this
									.authUser
									.token
								);
								_this
									.token =
									_this
									.authUser
									.token;
							} catch (
								e
							) {
								console
									.log(
										'存储用户对象错误'
									);
							}
							uni.showToast({
								title: "登录成功",
								icon: "none",
								duration: 2000
							});
							success()
						},
						fail: function(
							e
						) {
							uni.hideLoading()
							uni.showToast({
								title: "登录网络超时",
								icon: "none",
								duration: 2000
							});
						}
					})
				}
			})
		},
		fail: function(err) {
			uni.hideLoading()
			// 登录失败  
			uni.showToast({
				title: "登录网络超时或您未登录Apple账号" + JSON.stringify(err),
				icon: "none",
				duration: 2000
			});
			_this.isLogining = false
			_this.isLoginApp = false
		}
	});

}

/**登录成功的信息处理
infoRes 微信获取用户信息后的信息
*/
Vue.prototype.loginSuccess = function(data, infoRes, success, fail) {
	let _this = this
	_this.showLoginView = false;

	console.log("登录成功后存储用户信息进程开始")
	console.log("无需更新用户信息")
	uni.setStorageSync('updateUserInfo', true);
	uni.hideLoading()
	try { //同步存储用户信息
		_this.authUser = data.session_user
		// console.log(_this.authUser)
		uni.setStorageSync('authUser', JSON.stringify(_this.authUser));
		uni.setStorageSync('token', data.token);
		uni.setStorageSync('openid', data.session_user.openId);
		_this.token = data.token;
	} catch (e) {
		console.log('存储用户对象错误');
	}
	success()
}

//文件上传相关的方法


/**得到文件后缀*/
// Vue.prototype.getSuffix = function(fileNameOrPath) {
// 	var last_len = fileNameOrPath.lastIndexOf(".");
// 	var len = fileNameOrPath.length;
// 	var pathf = fileNameOrPath.substring(last_len + 1, len);
// 	return pathf;
// }
Vue.prototype.getSingleName = function(srcName) {
	var single = md5(Number(Math.random().toString().substr(3, 5) + Date.now()).toString());
	var name = single + "." + FileUtils.getSuffix(srcName);
	return name;
}

var subscription = null;

Vue.prototype.cancelUploadOss = function() {
	subscription.unsubscribe() // 上传取消
}

/**上传成功后返回上传成功图片的key值（唯一键）*/
Vue.prototype.uploadSingleFile = function(fileName, filePath, onUploadSuccess, onUploadProgress,
	onUploadError) {
	let _this = this;
	_this.sendRequest({
		url: "api/file/qiniu/getToken",
		data: {},
		showLoading: 2,
		success: function(res) {
			var token = res.data;
			var newName = _this.getSingleName(fileName);
			newName = "userupload/" + newName;
			// console.log(token)
			// console.log(fileName, filePath)
			// console.log(newName)
			// 交给七牛上传
			qiniuUploader.upload(filePath, (res) => {
				// 每个文件上传成功后,处理相关的事情
				// 其中 info 是文件上传成功后，服务端返回的json，形式如
				// {
				//    "hash": "Fh8xVqod2MQ1mocfI4S4KpRL6D98",
				//    "key": "gogopher.jpg"
				//  }
				// 参考http://developer.qiniu.com/docs/v6/api/overview/up/response/simple-response.html

				// that.setData({
				// 	'imageURL': res.imageURL,
				// });

				// console.log('file url is: ');
				// console.log(res)

				console.log("上传结束上传文件名为:" + res.key);
				if (onUploadSuccess) {
					onUploadSuccess(res);
				}
			}, (error) => {
				console.log('error: ' + error);
				if (onUploadError) {
					onUploadError("上传网络超时");
				}
			}, {
				region: 'SCN',
				domain: _this.isRelease() ?
					'http://expressionqiniu.luozisong.top' :
					'http://expressionqiniu.luozisong.top', // // bucket 域名，下载资源时用到。如果设置，会在 success callback 的 res 参数加上可以直接使用的 ImageURL 字段。否则需要自己拼接
				key: newName, // [非必须]自定义文件 key。如果不设置，默认为使用微信小程序 API 的临时文件名
				// 以下方法三选一即可，优先级为：uptoken > uptokenURL > uptokenFunc
				uptoken: token, // 由其他程序生成七牛 uptoken
				// uptokenURL: 'UpTokenURL.com/uptoken', // 从指定 url 通过 HTTP GET 获取 uptoken，返回的格式必须是 json 且包含 uptoken 字段，例如： {"uptoken": "[yourTokenString]"}
				// uptokenFunc: function() {
				// 	return '[yourTokenString]';
				// }
			}, (res) => {
				// console.log('上传进度', res.progress)
				// console.log('已经上传的数据长度', res.totalBytesSent)
				// console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)
				let total = res.progress;
				console.log("进度：" + total + "% ");
				if (onUploadProgress) {
					onUploadProgress(total);
				}
			}, () => {
				// 取消上传
			}, () => {
				// `before` 上传前执行的操作
			}, (err) => {
				// `complete` 上传接受后执行的操作(无论成功还是失败都执行)
			});

			// var observer = {
			// 	next(res) {
			// 		let total = res.total;
			// 		console.log("进度：" + total.percent + "% ");
			// 		if (onUploadProgress) {
			// 			onUploadProgress(total.percent);
			// 		}
			// 	},
			// 	error(err) {
			// 		if (onUploadError) {
			// 			onUploadError("上传失败");
			// 		}
			// 	},
			// 	complete(res) {
			// 		console.log("上传结束上传文件名为:" + res.key);
			// 		if (onUploadSuccess) {
			// 			onUploadSuccess(res.key);
			// 		}
			// 	}
			// }

			// var observable = QN.qiniu.upload(file, newName, token, putExtra, config)
			// var subscription = QN.observable.subscribe(observer) // 上传开始
			// // var subscription = observable.subscribe(next, error, complete) // 这样传参形式也可以
		},
		fail: function(e) {
			uni.showToast({
				title: "登录网络超时",
				icon: "none",
				duration: 2000
			});
		}
	})
}
/**上传成功后返回上传成功图片的key值（唯一键）*/
Vue.prototype.uploadSingleFileByFile = function(file, onUploadSuccess, onUploadProgress,
	onUploadError) {
	// #ifdef  H5
	var fileName = file.name
	// #endif

	// #ifdef  MP-WEIXIN||APP-PLUS||MP-QQ
	var fileName = file.path
	// #endif
	this.uploadSingleFile(fileName, file.path, onUploadSuccess, onUploadProgress, onUploadError);
}


Vue.prototype.uploadTask = null;
Vue.prototype.uploadIndex = 0;
Vue.prototype.uploadList = null; //已上传的列表

Vue.prototype.uploadFilesToService = function(files, module, success, fail) { //上传文件到服务器
	uni.showLoading({
		mask: true,
		title: "上传中"
	});
	let _this = this;
	// console.log(files[0])
	if (this.uploadIndex == 0) {
		this.uploadList = []
	}

	uni.showLoading({
		mask: true,
		title: files.length > 1 ? "上传第" + (_this.uploadIndex + 1) + "张" : "上传中"
	});

	console.log("shangchuan    " + files[_this.uploadIndex].downloadPath)
	this.uploadTask = uni.uploadFile({
		url: this.baseUrl + "api/file/uploadCompressFiles2Oss", //仅为示例，非真实的接口地址
		filePath: files[_this.uploadIndex].path,
		name: 'uploadFile',
		formData: {
			// 'uploadFile': files[_this.uploadIndex],
			'module': module,
			'userId': _this.authUser.id
		},
		header: {
			"token": _this.token
		},
		success: (res) => {
			let data = JSON.parse(res.data);
			data = data.data
			_this.uploadList.push(data)
			// console.log("1111111111111")
			// console.log(data)
			_this.uploadIndex++;
			// console.log(_this.uploadIndex + "   " + files.length)
			if (_this.uploadIndex < files.length) { //可以继续上传
				success(_this.uploadList, _this.uploadIndex, files.length)
				_this.uploadFilesToService(files, module, success, fail)
			} else { //传到最后一张了
				uni.hideLoading()
				success(_this.uploadList, _this.uploadIndex, files.length)
				_this.uploadIndex = 0
			}

		},
		fail: (res) => {
			uni.hideLoading()
			fail(res.errMsg)
			console.log(res);
			_this.uploadIndex = 0
			uni.showToast({
				title: res.errMsg,
				icon: "none",
				duration: 2000
			});
		}
	});

	// this.uploadTask.onProgressUpdate((res) => {
	// 	// console.log('上传进度' + res.progress);
	// 	// console.log('已经上传的数据长度' + res.totalBytesSent);
	// 	// console.log('预期需要上传的数据总长度' + res.totalBytesExpectedToSend);

	// 	uni.showLoading({
	// 		mask: true,
	// 		title: files.length > 1 ? "上传中第" + (_this.uploadIndex + 1) + "张" : "上传中"
	// 	});

	// 	// 测试条件，取消上传任务。
	// 	// if (res.progress > 50) {
	// 	// 	uploadTask.abort();
	// 	// }
	// });
}

Vue.prototype.calcelUpload = function() { //获取待处理任务
	this.uploadTask.abort();
}

Vue.prototype.clearAuth = function() { //获取待处理任务
	uni.setStorageSync('authUser', "");
	uni.setStorageSync('token', "");
	uni.setStorageSync('userId', null);

	this.authUser = null;
	this.user = null;
}
/**
 * 对象是否为空
 * @param object
 * @returns {boolean}
 */
Vue.prototype.isEmpty = function(object) {
	if (object === null || object === "" || object === undefined) {
		return true
	} else {
		object = object + ""
		object = object.replace(/\s+/g, "")
		if (object === "") {
			return true;
		}
	}

	return false;
}



Vue.prototype.showModal = function(modal) { //展示模态弹窗
	if (this.isEmpty(modal.confirmText)) {
		// if (this.platform == 1) { //Android下确认按钮在左边所以这里做一个映射把取消变成确定，确定变成取消
		// 	modal.confirmText = "取消"
		// } else {
		modal.confirmText = "确认"
		// }

	}
	if (this.isEmpty(modal.cancelText)) {
		// if (this.platform == 1) { //Android下确认按钮在左边所以这里做一个映射把取消变成确定，确定变成取消
		// modal.cancelText = "确认"
		// } else {
		modal.cancelText = "取消"
		// }
	}
	if (this.isEmpty(modal.confirmColor)) {
		modal.confirmColor = "#00aaff"
	}
	if (this.isEmpty(modal.cancelColor)) {
		modal.cancelColor = "#848484"
	}
	if (this.isEmpty(modal.showCancel)) {
		modal.showCancel = true
	}
	if (this.isEmpty(modal.title)) {
		modal.title = ""
	}
	// console.log(modal)
	if (this.platform == 1) { //Android下确认按钮在左边所以这里做一个映射把取消变成确定，确定变成取消
		uni.showModal({
			title: modal.title,
			content: modal.content,
			showCancel: modal.showCancel,
			confirmColor: modal.cancelColor,
			cancelColor: modal.confirmColor,
			confirmText: modal.cancelText,
			cancelText: modal.confirmText,
			complete: function(res) {
				// console.log(res)
				if (res.confirm) {
					if (modal.cancel != null) {
						modal.cancel()
					}
				} else {
					if (modal.confirm != null) {
						modal.confirm()
					}
				}
			}
		})
	} else {
		uni.showModal({
			title: modal.title,
			content: modal.content,
			showCancel: modal.showCancel,
			confirmColor: modal.confirmColor,
			cancelColor: modal.cancelColor,
			confirmText: modal.confirmText,
			cancelText: modal.cancelText,
			complete: function(res) {
				if (res.confirm) {
					if (modal.confirm != null) {
						modal.confirm()
					}
				} else if (res.cancel) {
					if (modal.cancel != null) {
						modal.cancel()
					}
				}
			}
		})
	}

	return;
}

/**
 * 看一次视频广告
 * @param object
 * @returns {boolean}
 */
Vue.prototype.lookVideo = function(refresh) {
	let _this = this

	// #ifdef MP-QQ
	uni.showLoading({
		title: "加载中",
		mask: true
	})
	let videoAd = qq.createRewardedVideoAd({
		adUnitId: "71820ce3674786f5fa73d7d2d3e40a14"
	})

	videoAd.onError(function(res) {
		console.log('videoAd onError', res)
	})
	videoAd.onLoad(function(res) {
		console.log('videoAd onLoad', res)
	})
	videoAd.onClose(function(res) {
		if (res.isEnded) {
			let lastUpdateTime = uni.getStorageSync('lookVideoLastUpdateTime');
			if (lastUpdateTime != null && Date.now() - Number(lastUpdateTime) <= 5 * 1000) { //每5秒可以触发一次
				return
			}
			uni.setStorageSync("lookVideoLastUpdateTime", Date.now())

			_this.sendRequest({
				url: "api/task/item/achieveTaskItem",
				data: {
					type: 9,
				},
				page: _this,
				method: "POST",
				success: function(res) {
					loading = false
					refresh()
				},
				fail: function(e) {
					loading = false
				}
			})
		} else {
			_this.showModal({
				content: "需要观看完成视频才能获得奖励哦",
				confirmText: "我知道了",
				showCancel: false,
				confirm: function() {

				}
			})
		}
		console.log('videoAd onClose', res)
	})

	videoAd.load()
		.then(() => {
			console.log('激励视频加载成功');
			uni.hideLoading()
			videoAd.show().then(() => {
					console.log('激励视频 广告显示成功')
				})
				.catch(err => {
					console.log('激励视频 广告显示失败')
				})
		})
		.catch(err => {
			uni.hideLoading()
			console.log('激励视频加载失败');
		})
	// #endif

	// #ifdef MP-TOUTIAO
	// 创建实例
	let ad = tt.createRewardedVideoAd({
		adUnitId: "wkdltgzvxopzpe3724",
	});

	// 监听错误
	ad.onError((err) => {
		tt.hideLoading();
		switch (err.errCode) {
			case 1004:
				// 无合适的广告
				uni.showModal({
					content: "暂无合适广告，请稍后再试",
					showCancel: false
				})
				break;
			default:
				// 更多请参考错误码文档
		}
	});

	// 监听视频播放完成
	ad.onClose((data) => {
		tt.hideLoading();
		if (data.isEnded) {
			console.log("观看了", data.count, "个视频");
			_this.sendRequest({
				url: "api/task/item/achieveTaskItem",
				data: {
					type: 9,
				},
				page: _this,
				method: "POST",
				success: function(res) {
					refresh()
				},
				fail: function(e) {}
			})
		} else {
			console.log("未观看完视频");
			_this.showModal({
				content: "需要观看完成视频才能获得奖励哦",
				confirmText: "我知道了",
				showCancel: false,
				confirm: function() {

				}
			})
		}
	});

	// 预加载资源
	ad.load();
	ad.show();
	// #endif

}

/**
 * 看一次视频广告
 * @param object
 * @returns {boolean}
 */
Vue.prototype.lookWindowsAd = function(adId) {
	let _this = this

	// #ifdef MP-QQ
	/* 建议放在需要展示插屏广告的时机执行 */
	try {
		let InterstitialAd = qq.createInterstitialAd({
			adUnitId: adId
		});
		InterstitialAd.load().catch((err) => {
			console.error('load', err)
		})
		InterstitialAd.onLoad(() => {
			console.log('onLoad event emit')
			/* 建议放在需要展示插屏广告的时机执行 */
			InterstitialAd.show().catch((err) => {
				console.error('show', err)
			})
		})
		InterstitialAd.onClose(() => {
			console.log('close event emit')
		})
		InterstitialAd.onError((e) => {
			console.log('error', e)
		})

	} catch (e) {
		//TODO handle the exception
	}
	// #endif

}

/**
 * 得到绘制次数
 * 
 * @param object
 * @returns {boolean}
 */
Vue.prototype.initUnReadTaskCount = function() {
	let userId = uni.getStorageSync("userId")
	if (this.isEmpty(userId)) {
		return
	}
	this.sendRequest({
		url: "api/drawtask/getUnReadTaskCount",
		data: {
			userId: userId
		},
		method: "GET",
		hintCodeMsg: 2,
		showLoading: 2,
		page: this,
		success: function(res) {
			let unReadCount = res.data
			if (unReadCount > 0) {
				uni.setTabBarBadge({
					index: 3,
					text: unReadCount + ""
				})
			} else {
				uni.removeTabBarBadge({
					index: 3
				})
			}

		},
		fail: function(e) {}
	})
}
/**
 * 初始化未读消息数量
 * 
 * @param object
 * @returns {boolean}
 */
Vue.prototype.initUnReadMessageCount = function(refresh) {
	let _this = this
	let userId = uni.getStorageSync("userId")
	if (this.isEmpty(userId)) {
		return
	}
	this.sendRequest({
		url: "api/messagebox/getUserUnReadMessageCount",
		data: {
			userId: userId
		},
		method: "GET",
		hintCodeMsg: 2,
		showLoading: 2,
		page: this,
		success: function(res) {
			let unReadCount = res.data

			if (unReadCount > 0) {
				uni.setTabBarBadge({
					index: 2,
					text: unReadCount + ""
				})
				if (_this.getLastMessageCount() < unReadCount && refresh != null)
					refresh(unReadCount)

			} else {
				uni.removeTabBarBadge({
					index: 2
				})
			}


			uni.setStorageSync("unReadMessageCount", unReadCount)

		},
		fail: function(e) {}
	})
}
/**
 * 得到上一次消息的总数，用来比较是否需要更新列表
 * 
 */
Vue.prototype.getLastMessageCount = function() {
	let count = uni.getStorageSync("unReadMessageCount")
	if (count == null || count == undefined) {
		count = 0
	}
	return count
}

/**
 * 得到绘制次数
 * 
 */
Vue.prototype.getGenCount = function() {
	//记录绘制次数
	let genCount = uni.getStorageSync("genCount")
	try {
		genCount = parseInt(genCount);
	} catch (e) {
		console.log("转换失败")
		genCount = 0
	}
	if (genCount == null || genCount == undefined || genCount == NaN || genCount == "NaN" || isNaN(genCount)) {
		genCount = 0;
	}

	return genCount
}


/**
 * 拉去描述词列表(每个小时只能拉去一次)
 * 
 * @param delay 当取缓存数据时的模拟延时，主要为了不卡屏幕,因为数据量一般较大
 * @returns {boolean}
 */
Vue.prototype.getDrawWordTreeAll = function(delay, success, fail) {
	let _this = this
	let allList = []
	let s = uni.getStorageSync('drawWord');
	if (!this.isEmpty(s)) {
		allList = JSON.parse(s)
	}
	let lastUpdateTime = uni.getStorageSync('drawWordLastUpdateTime');

	if (lastUpdateTime == null || Date.now() - Number(lastUpdateTime) > 60 * 60 * 1000) { //每小时可以更新一次
		let data = {
			type: 10
		}
		this.sendRequest({
			url: "api/drawword/getTreeAll",
			data: data,
			page: _this,
			method: "GET",
			showLoading: 2,
			success: function(res) {
				allList = res.data;

				uni.setStorageSync('drawWord', JSON.stringify(allList));
				uni.setStorageSync('drawWordLastUpdateTime', Date.now());
				//获取的所有层级的使用次数归0
				for (var i = 0; i < allList.length; i++) {
					let children = allList[i].children
					allList[i].useNum = 0
					if (children != null) {
						for (var j = 0; j < children.length; j++) {
							children[j].useNum = 0
						}
					}
				}
				success(allList)
			},
			fail: function(e) {
				fail("获取失败")
			}
		})
	} else {
		setTimeout(function() {
			success(allList)
		}, delay)
	}
}

/**
 * 获取会员限制(每个小时只能拉去一次)
 * 
 * @param object
 * @returns {boolean}
 */
Vue.prototype.getVipLimitByTime = function(success, fail) {
	let _this = this
	let vip = {}
	let s = uni.getStorageSync('vipLimit');
	if (!this.isEmpty(s)) {
		vip = JSON.parse(s)
	}

	let lastUpdateTime = uni.getStorageSync('vipLimitLastTime');

	if (lastUpdateTime == null || Date.now() - Number(lastUpdateTime) > 24 * 60 * 60 * 1000) { //每24小时可以更新一次
		uni.setStorageSync('vipLimitLastTime', 0);
		let data = {
			type: 10
		}
		this.sendRequest({
			url: "api/auth/user/vip/getVipLimit",
			data: data,
			page: _this,
			method: "POST",
			showLoading: 2,
			success: function(res) {
				vip = res.data;

				uni.setStorageSync('vipLimit', JSON.stringify(vip));
				uni.setStorageSync('vipLimitLastTime', Date.now());
				success(vip)

			},
			fail: function(e) {
				fail("获取失败")
			}
		})
	} else {
		success(vip)
	}
}
/**
 * 替换所有相关字符
 * 
 * @param object
 * @returns {boolean}
 */
Vue.prototype.replaceAll = function(input, toReplace, replaceWith) {
	return drawWordUtils.replaceAll(input, toReplace, replaceWith);
}
//中文符号替换成英文
Vue.prototype.replaceCharaterToComma = function(prompt) {
	// prompt = this.replaceAll(prompt, '，', ",");
	// prompt = this.replaceAll(prompt, '。', ",")
	// prompt = this.replaceAll(prompt, '、', ",")
	// prompt = this.replaceAll(prompt, '（', "(")
	// prompt = this.replaceAll(prompt, '）', ")")
	// prompt = this.replaceAll(prompt, '：', ":")
	return drawWordUtils.replaceCharaterToComma(prompt);
}

Vue.prototype.setWindowsHW = function(height, width) {
	uni.setStorageSync("windowsHeight", height)
	uni.setStorageSync("windowsWidth", width)
}

Vue.prototype.getWindowsHeight = function() {
	let height = uni.getStorageSync("windowsHeight")
	if (height == null) {
		height = 500
	}
	return height
}

/**是否可以刷新任务的标记*/
Vue.prototype.setRefreshTask = function(flag) {
	uni.setStorageSync("refreshTask", flag)
}

/**是否可以刷新任务的标记*/
Vue.prototype.canRefreshTask = function() {
	let flag = uni.getStorageSync("refreshTask")
	if (flag == null || flag == undefined) {
		return true
	}
	return flag
}


Vue.prototype.getWindowsWidth = function() {
	let width = uni.getStorageSync("windowsWidth")
	if (width == null) {
		width = 500
	}
	return width
}
Vue.prototype.saveClientId = function(authUser) {
	let _this = this
	if (authUser == null || authUser == undefined) {
		return
	}


	let time = (new Date()).getTime();
	if (_this.lastSaveCidTime != null && time - _this.lastSaveCidTime < 12 * 60 * 60 * 1000) { //12小时保存一次
		console.log("短时间内多次保存cid，跳过本次请求");
		return
	}

	let cid = uni.getStorageSync("clientId")

	setTimeout(function() {
		_this.sendRequest({
			url: "api/push/saveUserCid",
			data: {
				userId: authUser.id,
				cid: cid
			},
			page: _this,
			hintCodeMsg: 2,
			showLoading: 2,
			method: "POST",
			success: function(res) {
				_this.lastSaveCidTime = time

				console.log("保存CID成功" + time)
			},
			fail: function(e) {}
		})
	}, 3000)

}

Vue.prototype.setMessageReceive = function(messageId) { //设置消息回执
	let _this = this

	setTimeout(function() {
		_this.sendRequest({
			url: "api/messagebox/setMessageReceive",
			data: {
				id: messageId
			},
			page: _this,
			hintCodeMsg: 2,
			showLoading: 2,
			method: "POST",
			success: function(res) {},
			fail: function(e) {}
		})
	}, 3000)


}

Vue.prototype.getPhoneLevel = function(messageId) { //得到电话等级等级越高粗略认为手机运行速度越快，但这并不是绝对的
	let _this = this

	let screenHeight = uni.getStorageSync("screenHeight")

	if (screenHeight == null || screenHeight == '') { //默认为2级
		return 2
	}

	if (screenHeight > 0 && screenHeight <= 800) {
		return 1
	} else if (screenHeight > 800 && screenHeight <= 1280) {
		return 2
	} else if (screenHeight > 1280 && screenHeight <= 1920) {
		return 3
	} else if (screenHeight > 1920 && screenHeight <= 2200) {
		return 4
	} else if (screenHeight > 2200 && screenHeight <= 2560) {
		return 5
	} else if (screenHeight > 2560) {
		return 6
	}

}

/**
 * @description 进行延时，以达到可以简写代码的目的 比如: await uni.$uv.sleep(20)将会阻塞20ms
 * @param {number} value 堵塞时间 单位ms 毫秒
 * @returns {Promise} 返回promise
 */
Vue.prototype.sleepSync = function(value = 30) {
	return new Promise((resolve) => {
		setTimeout(() => {
			resolve()
		}, value)
	})

}

/**
跳转应用市场
 */
Vue.prototype.jumpStore = function(value = 30) {
	if (this.platform == 1) {
		let appurl =
			"market://details?id=com.xsdr.aidraw"; //这个是通用应用市场，如果想指定某个应用商店，需要单独查这个应用商店的包名或scheme及参数  
		plus.runtime.openURL(appurl);
	} else if (this.platform == 2) {
		console.log("跳转APP store市场")
		plus.runtime.launchApplication({
			action: 'itms-apps://itunes.apple.com/cn/app/id6449507699?mt=8'
		}, function(e) {
			console.log(
				'Open system default browser failed: ' +
				e.message);
		});

	}
}
/**
 *根据权重值计算显示的背景色
 */
Vue.prototype.getPromptBackgroundByWeight = function(word) {
	let transfer = drawWordUtils.getPromptTransfer(word)
	if (transfer.weight == null || transfer.weight == 1) {
		return "#e6f4ff"
	} else if (transfer.weight < 1) {
		return "#f4f4f4"
	} else if (transfer.weight >= 1.1 && transfer.weight < 1.2) {
		return "#ffedee"
	} else if (transfer.weight >= 1.2 && transfer.weight < 1.3) {
		return "#FFDFE1"
	} else if (transfer.weight >= 1.3 && transfer.weight < 1.4) {
		return "#FFD1D4"
	} else if (transfer.weight >= 1.4 && transfer.weight < 1.5) {
		return "#FFC3C7"
	} else if (transfer.weight >= 1.5 && transfer.weight < 1.6) {
		return "#FFB5BA"
	} else if (transfer.weight >= 1.6 && transfer.weight < 1.7) {
		return "#FFA7AD"
	} else if (transfer.weight >= 1.7 && transfer.weight < 1.8) {
		return "#FF99A0"
	} else if (transfer.weight >= 1.8 && transfer.weight < 1.9) {
		return "#FF8B93"
	} else if (transfer.weight >= 1.9 && transfer.weight < 2) {
		return "#FF7D86"
	} else if (transfer.weight >= 2 && transfer.weight < 2.1) {
		return "#FF6F79"
	}
	return "#fffbfb"
}

/**
上传图片并分析
 */
Vue.prototype.uploadFileAsync = function(filePath, module, success, fail) {
	let _this = this
	uni.showLoading({
		mask: true,
		title: "上传文件中"
	});

	uni.uploadFile({
		url: _this.baseUrl + 'api/file/uploadSingleFile', //仅为示例，非真实的接口地址
		filePath: filePath,
		header: {
			"token": _this.token,
			"Platform": _this.platform
		},
		name: 'uploadFile',
		formData: {
			'module': module
		},
		success: (uploadRes) => {
			console.log(uploadRes)
			let res = null;
			// #ifndef MP-BAIDU
			res = JSON.parse(uploadRes.data)
			// #endif
			// #ifdef MP-BAIDU
			res = uploadRes.data
			// #endif
			let fileCommon = res.data

			uni.hideLoading()
			if (res.code == 200) {
				let selectFilePath = filePath
				if (success != null) {
					success(selectFilePath, fileCommon)
				}
			} else if (res.code == 1100) { //登录过期
				//展示过期登录框
				uni.showModal({
					title: '提示',
					content: res.msg,
					confirmText: "重新登录",
					showCancel: true,
					success: function(res) {
						if (res.confirm) {
							uni.redirectTo({
								url: '/pages/login/login'
							});
							_this.showLoginView = false;
						} else if (res.cancel) {
							console.log('用户点击取消');
							_this.showLoginView = false;
						}
					}
				});
				fail("登录过期")
			} else {
				uni.showModal({
					content: res.msg,
					showCancel: false
				})
				fail(res.msg)
			}
		},
		fail: function(res) {
			uni.showModal({
				content: "上传失败:" + JSON.stringify(res),
				showCancel: false
			})
			fail(res.msg)
			uni.hideLoading()
		}
	});
}

/**
 *是否有某个权限
 * @param type 1.外部存储权限
 */
Vue.prototype.requestPermissions = async function(permission, success, fail) {
	let _this = this
	plus.android.requestPermissions(
		permission,
		function(result) {
			// let res = 0;
			// for (let i = 0; i < result.granted.length; i++) {
			// 	let permission = result.granted[i];
			// 	console.log("已获取的权限：", permission);
			// 	res = 1;
			// }
			let deniedCount = 0
			for (let i = 0; i < result.deniedPresent.length; i++) {
				// let permission = result.deniedPresent[i];
				// console.log("本次已拒绝的权限：", permission);
				deniedCount++
			}
			for (let i = 0; i < result.deniedAlways.length; i++) {
				// let permission = result.deniedAlways[i];
				// console.log("永久拒绝的权限：", permission);
				deniedCount++
			}
			console.log(result)

			if (deniedCount == 0) {
				success()
			} else {
				uni.showModal({
					content: "权限被拒绝无法继续向下操作，请手动允许APP获得权限后再试",
					showCancel: false
				})
				fail()
			}
		},
		(error) => {
			// reject({
			// 	code: 2,
			// 	data: `code:${error.code},msg:${error.message}!`,
			// });
			fail()
		}
	);



}
/**
 *是否有某个权限
 * @param type 1.外部存储权限
 */
Vue.prototype.isHasAndroidPermission = async function(type, success) {
	let _this = this

	return new Promise((resolve) => {
		// #ifdef APP-PLUS
		try {
			if (_this.platform == 1) {
				uni.showLoading({
					mask: true,
					title: "请求权限中"
				});


				let flag = false;
				let compat = plus.android.importClass('androidx.core.content.ContextCompat')
				let context = plus.android.runtimeMainActivity() //上下文
				let permission = []
				if (type == 1) { //读写权限
					permission = [
						'android.permission.READ_EXTERNAL_STORAGE',
						'android.permission.WRITE_EXTERNAL_STORAGE',
						'android.permission.CAMERA'
					]
				} else if (type == 2) { //相机权限
					permission = ['android.permission.CAMERA']
				}

				//result 返回0则表示已授权该权限，为-1则未授权

				let unGetCount = 0

				for (var i = 0; i < permission.length; i++) {
					let result = compat.checkSelfPermission(context, permission[i])
					if (result != 0) { //未获得的数量
						unGetCount++
					}
				}

				// console.log("result   " + result)
				uni.hideLoading()
				if (unGetCount > 0) {
					if (type == 1) {
						_this.showModal({
							title: "为使APP正常使用将申请'读写外部存储权限和相机权限'",
							content: "获取后将用于上传或下载图片/文件",
							confirmText: "确认",
							confirm: function() {
								_this.requestPermissions(permission, function() {
									resolve(true)
								})

							}
						})
					} else if (type == 2) {
						_this.showModal({
							title: "为使APP正常使用将申请'相机权限'",
							content: "获取后将用于打开相机",
							confirmText: "确认",
							confirm: function() {
								_this.requestPermissions(permission, function() {
									resolve(true)
								})
							}
						})
					}

				} else {
					resolve(true)
				}
			} else {
				resolve(true)
			}
		} catch (e) { //失败的话默认不处理了
			//TODO handle the exception
			resolve(true)
		}

		// #endif

		// #ifndef APP-PLUS
		resolve(true)
		// #endif
	})

}


/**
 *是否有某个后台权限，
 * @@param {permissionKey} 判断键的名称
 */
Vue.prototype.isHadPermission = async function(permissionKey) {
	let _this = this;
	// console.log(file)
	if (this.authUser != null) {
		for (var i = 0; i < this.authUser.accessList.length; i++) {
			if (this.authUser.accessList[i] == "superManager") { //超级管理员权限默认全部都有
				return true
			}
			if (this.authUser.accessList[i] == permissionKey) {
				return true
			}
		}
	}
	return false


}


Vue.prototype.getLocation = function(success, fail) { //根据平台类型不同来获取位置
	let _this = this;
	console.log("开始定位")
	if (this.platform === 3 || this.platform === 5) { //h5直接获取固定的测试位置地址
		this.lat = 30.486633;
		this.lng = 104.130763;
		success(this.lat, this.lng)
	} else {
		uni.showLoading({
			mask: true,
			title: "正在定位"
		});
		// console.log("11111111")
		if (!this.isEmpty(this.lat) && !this.isEmpty(this.lng) &&
			this.lat != 0 && this.lng != 0) {
			uni.hideLoading()
			// console.log("2222222222")
			success(this.lat, this.lng)
			return
		}
		// console.log("3333333")
		uni.getLocation({
			type: 'gcj02',
			success: function(res) {
				console.log(res)
				console.log('当前位置的经度：' + res.longitude);
				console.log('当前位置的纬度：' + res.latitude);
				uni.hideLoading()
				_this.lat = res.latitude;
				_this.lng = res.longitude;
				console.log("44444444")
				success(res.latitude, res.longitude)
			},
			fail: function(msg) {
				fail(msg)
			}
		});
	}

}